package com.chezhujie.www.controller;


import com.alibaba.fastjson.JSONObject;
import com.chezhujie.www.constant.AesConstant;
import com.chezhujie.www.core.image.ImageUtils;
import com.chezhujie.www.core.page.Pagination;
import com.chezhujie.www.domain.Czjawardon;
import com.chezhujie.www.domain.Czjawardstock;
import com.chezhujie.www.domain.Czjroulette;
import com.chezhujie.www.domain.vo.CzjawardonVO;
import com.chezhujie.www.domain.vo.CzjawardonVOB;
import com.chezhujie.www.domain.vo.CzjawardonVOR;
import com.chezhujie.www.service.CzjawardapiService;
import com.chezhujie.www.service.CzjawardonService;
import com.chezhujie.www.service.CzjawardstockService;
import com.chezhujie.www.service.CzjrouletteService;
import com.chezhujie.www.utils.*;

import net.coobird.thumbnailator.Thumbnails;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.awt.Color;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;





@Controller
@RequestMapping("/roulette")
public class CzjrouletteController extends BaseController {
	private static final Logger log = LoggerFactory.getLogger(CzjrouletteController.class);
	public CzjrouletteController() {
	}


	/**
	 * czj_awardstock 奖品库新增页面
	 *
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjthingId.do")
	public void czjthingId(HttpServletRequest request,
						   String discountShop,
						   HttpServletResponse response, ModelMap model) throws Exception {
		try {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("awardstockId", discountShop);
			Czjawardstock czjawardstock = czjawardstockService.getCzjawardstock(param);
			if(czjawardstock == null){
				czjawardstock = new Czjawardstock();
			}
			jsonResult(1, "", "获取奖品库信息成功",czjawardstock, response);
		} catch (Exception e) {
			log.error("czjthingId.do:", e);
			throw e;
		}

	}


	/**
	 * czj_roulette  二维码页面
	 *
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjcodeEditcode.do")
	public String qrtwoCode(HttpServletRequest request,
							String rouletteId,
							ModelMap model) {
		return "";
		
	}


	/**
	 * czj_roulette  二维码页面
	 *
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjrouletteEditcode.do")
	public String qrCode(HttpServletRequest request,
						 String rouletteId,
						 ModelMap model) {
		StringBuffer url = request.getRequestURL();
		String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append("/").toString();
		String index = request.getParameter("ext2");
		String onlineType ="";
		if("1".equals(index)){
			onlineType ="luckdraw";
		}else{
			onlineType ="luckdraw";
		}
		request.setAttribute("tempContextUrl",tempContextUrl);
		request.setAttribute("bs",rouletteId);
		request.setAttribute("onlineType",onlineType);
		setDict(model);
		return "qrcode/index";
	}

	/**
	 * czj_roulette  优惠新增页面
	 *
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjrouletteActAdd.do")
	public String czjrouletteActAdd(HttpServletRequest request, ModelMap model) {
		Czjroulette czjroulette  = new Czjroulette();
		czjroulette.setExt2(request.getParameter("ext2"));
		Map<String, Object> param4 = new HashMap<String, Object>();
		List<Czjawardstock> czjawardstocks  = czjawardstockService.getCzjawardstockListALL(param4);
		model.addAttribute("czjawardstocks", czjawardstocks);
		model.addAttribute("czjroulette", czjroulette);
		setDict(model);
		return "roulette/czjrouletteActEdit";
	}

	/**
	 * czj_roulette  优惠新增页面
	 *
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjrouletteAdd.do")
	public String add(HttpServletRequest request, ModelMap model) {
		String html="";
		Czjroulette czjroulette  = new Czjroulette();
		czjroulette.setExt2(request.getParameter("ext2"));
		Map<String, Object> param4 = new HashMap<String, Object>();
		List<Czjawardstock> czjawardstocks  = czjawardstockService.getCzjawardstockListALL(param4);
		if("1".equals(czjroulette.getExt2())){
			html ="roulette/czjrouletteEdit";
		}
		if("2".equals(czjroulette.getExt2())){
			html ="roulette/czjrouletteEdit";
		}
		if("3".equals(czjroulette.getExt2())){
			html ="roulette/czjcodeEdit";
		}
		model.addAttribute("czjawardstocks", czjawardstocks);
		model.addAttribute("czjroulette", czjroulette);
		setDict(model);
		return html;
	}

	/**
	 * czj_roulette  优惠保存
	 *
	 * @param czjroulette
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjrouletteActSave.do")
	public String save(Czjroulette czjroulette,
					   HttpServletRequest request, ModelMap model) throws Exception{				
		try {
			Date endDate = czjroulette.getEndtime();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");		
			String DateEnd = sdf.format(endDate);
			String  endTimeStr = "23:59:59";
			String start = DateEnd.substring(0, 11);
			DateEnd = start + endTimeStr;				
			Date endtime = sdf.parse(DateEnd);		
			czjroulette.setEndtime(endtime);			
			//路径
			if(czjroulette.getRouletteId()!=null&&!czjroulette.getRouletteId().equals("")){
				// 编辑
				czjrouletteService.updateCzjroulette(czjroulette);
				model.addAttribute("message",2);
				//tlogService.insertTloger(LoggerHelper.getTloger(request, LoggerHelper.OPERATING, "编辑czj_roulette  优惠", "rouletteId="+czjroulette.getrouletteId()));
			} else {
				// 新增
				czjroulette.setCreatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
				czjroulette.setExt1("0");
				czjroulette.setDelFlag(0);
				czjrouletteService.insertCzjroulette(czjroulette);
				model.addAttribute("message",2);
				//tlogService.insertTloger(LoggerHelper.getTloger(request, LoggerHelper.OPERATING, "新增czj_roulette  优惠", "rouletteId="+czjroulette.getrouletteId()));
			}
		} catch (Exception e) {
			log.error("czjroulette save error:", e);
			throw e;
		}
		return "redirect:czjrouletteEdit.do?rouletteId="+czjroulette.getRouletteId();
	}

	/**
	 * czj_roulette  优惠保存
	 *
	 * @param czjroulette
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjrouletteSave.do")
	public String save(Czjroulette czjroulette,
					   @RequestParam(value = "first", required = false)  MultipartFile first,
					   @RequestParam(value = "second", required = false) MultipartFile second,
					   @RequestParam(value = "third", required = false) MultipartFile third,
					   @RequestParam(value = "four", required = false) MultipartFile four,
					   HttpServletRequest request, ModelMap model) throws Exception{
		String ext2 = czjroulette.getExt2();
		try {
			//路径
			String pathRoot = request.getSession().getServletContext()
					.getRealPath("");
			String path = "";
			// 轮盘中图片
			if (!first.isEmpty() && first.getSize()>0) {
				String uuid = UUID.randomUUID().toString().replaceAll("-", "");
				path = "/uploadvoteorder/" + uuid;
				File file = new File(pathRoot + "/uploadvoteorder");
				if (!file.exists()) {
					file.mkdir();
				}
				 first.transferTo(new File(pathRoot + path+".jpg"));
				/*Thumbnails.of(c).scale(0.25f).outputFormat("jpg")
	          .toFile(new File(pathRoot + path+"czj"));//中等图
	          */		
//				Thumbnails.of(new FileInputStream(new File(pathRoot + path+"."+imageName))).scale(1f).outputFormat("jpg").
//				outputQuality(0.25f).toFile(new File(pathRoot + path));
//				 Picture.resizePNG(pathRoot + path+"."+imageName, pathRoot + path+".jpg", 750, 750, true);
//					ImageUtils.fromFile(new File(pathRoot + path+".jpg"))
//					.quality(0.6f)
//					.fixedGivenSize(true)
//					.keepRatio(true)
//					.bgcolor(Color.WHITE)	//白色背景
//					.toFile(new File(pathRoot+path+"czj.jpg"));	
				//更新才设置图片路径
				czjroulette.setImgPath(path+".jpg");
			}
			// 指针图片
			if (!second.isEmpty() && second.getSize()>0) {
				String uuid = UUID.randomUUID().toString().replaceAll("-", "");
				path = "/uploadvoteorder/" + uuid;
				File file = new File(pathRoot + "/uploadvoteorder");
				if (!file.exists()) {
					file.mkdir();
				}
				second.transferTo(new File(pathRoot + path+".jpg"));
				/*Thumbnails.of(c).scale(0.25f).outputFormat("jpg")
	          .toFile(new File(pathRoot + path+"czj"));//中等图
	          */		
//				Thumbnails.of(new FileInputStream(new File(pathRoot + path+"."+imageName))).scale(1f).outputFormat("jpg").
//				outputQuality(0.25f).toFile(new File(pathRoot + path));
//				 Picture.resizePNG(pathRoot + path+"."+imageName, pathRoot + path+".jpg", 750, 750, true);
//					ImageUtils.fromFile(new File(pathRoot + path+".jpg"))
//					.quality(0.6f)
//					.fixedGivenSize(true)
//					.keepRatio(true)
//					.bgcolor(Color.WHITE)	//白色背景
//					.toFile(new File(pathRoot+path+"czj.jpg"));	
				//更新才设置图片路径
				czjroulette.setImgUrl(path+".jpg");
			}
			// 轮盘顶图片
			if (!third.isEmpty() && third.getSize()>0) {
				String uuid = UUID.randomUUID().toString().replaceAll("-", "");
				path = "/uploadvoteorder/" + uuid;
				File file = new File(pathRoot + "/uploadvoteorder");
				if (!file.exists()) {
					file.mkdir();
				}
				third.transferTo(new File(pathRoot + path+".jpg"));
				czjroulette.setExt4(path+".jpg");
			}
			// 轮盘底图片
			if (!four.isEmpty() && four.getSize()>0) {
				String uuid = UUID.randomUUID().toString().replaceAll("-", "");
				path = "/uploadvoteorder/" + uuid;
				File file = new File(pathRoot + "/uploadvoteorder");
				if (!file.exists()) {
					file.mkdir();
				}
				four.transferTo(new File(pathRoot + path+".jpg"));
				czjroulette.setExt5(path+".jpg");
			}				
			if(czjroulette.getRouletteId()!=null&&!czjroulette.getRouletteId().equals("")){
				// 编辑
				czjrouletteService.updateCzjroulette(czjroulette);
				model.addAttribute("message",2);
				//tlogService.insertTloger(LoggerHelper.getTloger(request, LoggerHelper.OPERATING, "编辑czj_roulette  优惠", "rouletteId="+czjroulette.getrouletteId()));
			} else {
				// 新增
				czjroulette.setCreatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
				czjroulette.setExt1("0");
				czjrouletteService.insertCzjroulette(czjroulette);
				model.addAttribute("message",2);
				//tlogService.insertTloger(LoggerHelper.getTloger(request, LoggerHelper.OPERATING, "新增czj_roulette  优惠", "rouletteId="+czjroulette.getrouletteId()));
			}
			return updatePrizes(czjroulette);


		} catch (Exception e) {
			log.error("czjroulette save error:", e);
			throw e;
		}

		//+"&ext3="+czjroulette.getExt3()
	}

	/**
	 * 更新优惠活动的奖品数量
	 * by tangwj
	 * @param czjroulette
	 * @return
	 */
	private String updatePrizes(Czjroulette czjroulette) {
		//查询轮盘下有多少个分配个体
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("rouletteId",czjroulette.getRouletteId());
		List<Czjawardon> czjawardonList = czjawardonService.getListEntity(param);
		List<Czjawardstock> czjawardstockList = czjawardstockService.queryAll();
		Map<String, Czjawardstock> msc = new HashMap<String, Czjawardstock>();
		for (Czjawardstock czjawardstock : czjawardstockList) {
			msc.put(czjawardstock.getAwardstockId(), czjawardstock);
		}
		Integer inputCount = Integer.valueOf(czjroulette.getExt3());

		List<Czjawardon> insertList = new ArrayList<Czjawardon>();
		List<Czjawardon> deleteList = new ArrayList<Czjawardon>();
		List<String> updateId = new ArrayList<String>();//要更新的stock主键
		if(inputCount>czjawardonList.size()){
			//你填写的要分配的个体大于分配个体，则 自动新增新的个体，并插入数据库
			int insertCount = inputCount - czjawardonList.size();
			for(int i=1;i<=insertCount;i++){
				Czjawardon czjawardon = new Czjawardon();
				czjawardon.setAwardonId(UUIDUtils.getUUID());
				czjawardon.setDelFlag(0);
				czjawardon.setCreatetime(new Date());
				czjawardon.setCount(0);
				czjawardon.setThingId(null);
				czjawardon.setShopId(czjroulette.getRouletteId());
				czjawardon.setPrice("0");
				czjawardon.setExt3(0);
				czjawardon.setExt1(String.valueOf(czjawardonList.size()+i));
				insertList.add(czjawardon);
			}
			for (Czjawardon czjawardon : insertList) {
				czjawardonService.insertCzjawardon(czjawardon);
			}
			return "redirect:czjawardonEdit.do?rouletteId="+czjroulette.getRouletteId();

		}else if(inputCount<czjawardonList.size()){
			//小于的情况下，则自动删除多余的个体，并更新数据库
			int updateCount = czjawardonList.size() - inputCount;

			for (int i = czjawardonList.size() - 1; i >= inputCount; i--) {
				Integer shengyuNum = czjawardonList.get(i).getCount()-czjawardonList.get(i).getExt3();//变动差值
				czjawardonList.get(i).setCount(czjawardonList.get(i).getExt3());
				czjawardonList.get(i).setDelFlag(1);
				Czjawardstock awardstock = msc.get(czjawardonList.get(i).getThingId());
				if(awardstock!=null){
					restoreNum(awardstock,czjawardonList.get(i));
					updateId.add(awardstock.getAwardstockId());
//					updateStock.add(awardstock);
				}

				deleteList.add(czjawardonList.get(i));
			}

			for (String s : updateId) {
				if(msc.containsKey(s)){
					czjawardstockService.updateCzjawardstock(msc.get(s));
				}
			}

			for (Czjawardon czjawardon : deleteList) {
				czjawardonService.updateCzjawardon(czjawardon);
			}
			return "redirect:czjawardonEdit.do?rouletteId="+czjroulette.getRouletteId();
		}else{
			return "redirect:czjawardonEdit.do?rouletteId="+czjroulette.getRouletteId();
		}
	}

	/**
	 * czj_roulette  优惠保存
	 *
	 * @param czjroulette
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjawardSave.do")
	public String czjawardSave(Czjroulette czjroulette,
							   String [] awardonIds,
							   String [] oldthingIds,
							   String [] thingIds,
							   String [] probabilitys,
							   Integer [] countnums,
							   String [] ext2s,
							   Integer [] ext3s,

							   String [] prizePaths,
							   String [] backgroundPaths,
							   String [] iscodes,

							   @RequestParam(value = "first", required = false)  MultipartFile[] first,
							   @RequestParam(value = "second", required = false) MultipartFile[] second,
							   HttpServletRequest request, ModelMap model) throws Exception{
		String ext2 = czjroulette.getExt2();			//路径
		String pathRoot = request.getSession().getServletContext()
				.getRealPath("");

		String [] prizePath = new String [thingIds.length];
		String [] backgroundPath = new String [thingIds.length];

		String path = "";
		// 第一张头像
		for(int i =0; i<first.length; i++ ){
			if (!first[i].isEmpty() && first[i].getSize()>0) {
				String uuid = UUID.randomUUID().toString().replaceAll("-", "");
				path = "/uploadvoteorder/" + uuid + "." + "jpg";
				File file = new File(pathRoot + "/uploadvoteorder");
				if (!file.exists()) {
					file.mkdir();
				}
				first[i].transferTo(new File(pathRoot + path));
				//更新才删
				String jpgPic = czjroulette.getImgPath();
				if(jpgPic != null && jpgPic.length()>5){
					jpgPic = jpgPic.substring(1, jpgPic.length());
				}
				deleteFile(pathRoot + jpgPic);
				//更新才设置图片路径
				prizePath[i] = path;;
			}
		}
		// 第二张头像
		for(int i =0; i<second.length; i++ ){
			if (!second[i].isEmpty() && second[i].getSize()>0) {
				String uuid = UUID.randomUUID().toString().replaceAll("-", "");
				path = "/uploadvoteorder/" + uuid + "." + "jpg";
				File file = new File(pathRoot + "/uploadvoteorder");
				if (!file.exists()) {
					file.mkdir();
				}
				second[i].transferTo(new File(pathRoot + path));
				//更新才删
				String jpgPic = czjroulette.getImgUrl();
				if(jpgPic != null && jpgPic.length()>5){
					jpgPic = jpgPic.substring(1, jpgPic.length());
				}
				deleteFile(pathRoot + jpgPic);
				//更新才设置图片路径
				backgroundPath[i] = path;
			}
		}
		try {
			Map<String, Object> param1 = new HashMap<String, Object>();
			param1.put("shopId", czjroulette.getRouletteId());
			//还原数据
			for(int i= 0;i<thingIds.length; i++){
				Map<String, Object> param2 = new HashMap<String, Object>();
				param2.put("awardonId",awardonIds[i]);
				//查出奖品信息
				Czjawardon czjawardon = czjawardonService.getCzjawardon(param2);

				Map<String, Object> param3 = new HashMap<String, Object>();
				param3.put("awardstockId", thingIds[i]);
				//查出奖品库信息
				Czjawardstock czjawardstock = czjawardstockService.getCzjawardstock(param3);

				if(czjawardstock!=null){
					//获取奖品库剩余数量
					int shengyunum = czjawardstock.getShengyunum();
					//页面更新数量                    分配数量               抽取数量
					int updatenum = countnums[i]-ext3s[i];
					//更新的数据
					czjawardstock.setShengyunum(shengyunum);

					if(czjawardon==null){
						//实际更新数量
						shengyunum = shengyunum - updatenum;
						//更新的数据
						czjawardstock.setShengyunum(shengyunum);
					}else{
						if(czjawardon.getExt3()==null){
							czjawardon.setExt3(0);
						}
						if(czjawardon.getCount()==null){
							czjawardon.setCount(0);
						}
						//更新的数据
						int oldnum  =  czjawardon.getCount() - Integer.valueOf(czjawardon.getExt3());
						//旧的和新的相减
						int changenum  = oldnum - updatenum;
						//相差的数据加起来
						shengyunum = shengyunum + changenum;
						czjawardstock.setShengyunum(shengyunum);
						//如果oldthingIds[i]不等于thingIds时
						if( !oldthingIds[i].equals(thingIds[i]) && !"-1".equals(oldthingIds[i])){
							Map<String, Object> map = new HashMap<String, Object>();
							map.put("awardstockId", oldthingIds[i]);
							//查出奖品库信息
							Czjawardstock czjawardstock2 = czjawardstockService.getCzjawardstock(map);
							//获取奖品库剩余数量
							int shengyunum2 = czjawardstock2.getShengyunum();
							//页面更新数量                             分配数量                                                                抽取数量
							int updatenum2 = czjawardon.getCount()-Integer.valueOf(czjawardon.getExt3());
							//旧数据加
							shengyunum2 = shengyunum2 + updatenum2;
							//新数据减
							shengyunum = shengyunum - updatenum2;
							//更新的数据
							czjawardstock2.setShengyunum(shengyunum2);
							//更新旧数据
							czjawardstock.setShengyunum(shengyunum);
							czjawardstockService.updateCzjawardstock(czjawardstock2);
							//新的就分配为0
							ext3s[i]= 0;
						}
					}
					czjawardstockService.updateCzjawardstock(czjawardstock);
				}
			}
			//逻辑删除删除对应的轮盘Id
			czjawardonService.deleteCzjawardonByR(param1);
			if(thingIds!=null){
				for(int i= 0;i<thingIds.length; i++){
					Czjawardon czjawardon = new Czjawardon();
					czjawardon.setAwardonId(awardonIds[i]);
					czjawardon.setThingId(thingIds[i]);
					czjawardon.setProbability(Double.valueOf(probabilitys[i]));
					czjawardon.setShopId(czjroulette.getRouletteId());
					czjawardon.setExt1(String.valueOf((i+1)));
					czjawardon.setExt3(ext3s[i]);
					czjawardon.setCount(countnums[i]);
					czjawardon.setTheme(iscodes[i]);
					czjawardon.setCreatetime(new Date());
					//不相等的时候才设置PrizePath
					if(!(prizePath[i]==null)){
						czjawardon.setPrizePath(prizePath[i]);
					}else{
						czjawardon.setPrizePath(prizePaths[i]);
					}
					//不相等的时候才设置BackgroundPath
					if(!(backgroundPath[i]==null)){
						czjawardon.setBackgroundPath(backgroundPath[i]);
					}else{
						czjawardon.setBackgroundPath(backgroundPaths[i]);
					}
					czjawardon.setDelFlag(0);

					Map<String, Object> czjawardon3param = new HashMap<String, Object>();
					czjawardon3param.put("awardonId", awardonIds[i]);
					Czjawardon czjawardon3 = czjawardonService.getCzjawardon(czjawardon3param);
					if(czjawardon3==null){
						czjawardonService.insertCzjawardon(czjawardon);
					}else{
						czjawardonService.updateCzjawardon(czjawardon);
					}

				}
			}
		} catch (Exception e) {
			log.error("czjroulette save error:", e);
			throw e;
		}
		return "redirect:czjrouletteActList.do";
	}


	/**
	 * czj_roulette  优惠保存
	 *
	 * @param czjroulette
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjrouletteSaveExt1.do")
	public String saveExt1(Czjroulette czjroulette,
						   HttpServletRequest request, ModelMap model) throws Exception{
		try {
			if(czjroulette.getRouletteId()!=null&&!czjroulette.getRouletteId().equals("")){
				// 编辑
				String  message =null;

				Map<String, Object> param1 = new HashMap<String, Object>();
				param1.put("shopId", czjroulette.getRouletteId());
				List<CzjawardonVO> czjawardons = czjawardapiService.getawardonListALLVO(param1);
				if(czjawardons.size()<1){
					message = "3";
					model.addAttribute("message",message);
					return "redirect:czjrouletteEdit.do?rouletteId="+czjroulette.getRouletteId();
				}

				czjrouletteService.updateCzjroulette(czjroulette);



				if("1".equals(czjroulette.getExt1())){
					message = "1";
				}
				if("0".equals(czjroulette.getExt1())){
					message = "0";
				}
				model.addAttribute("message",message);
				//tlogService.insertTloger(LoggerHelper.getTloger(request, LoggerHelper.OPERATING, "编辑czj_roulette  优惠", "rouletteId="+czjroulette.getrouletteId()));
			} else {
				// 新增
/*				czjroulette.setCreatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
				czjrouletteService.insertCzjroulette(czjroulette);*/
				//tlogService.insertTloger(LoggerHelper.getTloger(request, LoggerHelper.OPERATING, "新增czj_roulette  优惠", "rouletteId="+czjroulette.getrouletteId()));
			}
		} catch (Exception e) {
			log.error("czjroulette save error:", e);
			throw e;
		}

		return "redirect:czjrouletteEdit.do?rouletteId="+czjroulette.getRouletteId();
	}

	/**
	 * czj_roulette  优惠删除
	 *
	 * @param ids
	 * @return
	 */
	@RequestMapping("czjrouletteDelete.do")
	public String delete(@RequestParam("ids") List<String> rouletteIdList,String ext2) throws Exception{
		try {
			if (rouletteIdList != null) {
				czjrouletteService.deleteCzjroulette(rouletteIdList);
			}
		} catch (Exception e) {
			log.error("czjroulette delete error:", e);
			throw e;
		}
		return "redirect:czjrouletteActList.do";

	}

	/**
	 * czj_roulette  奖品编辑
	 *
	 * @param rouletteId
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjawardondetails.do")
	public String czjawardondetails(String rouletteId, HttpServletRequest request, ModelMap model) throws Exception{
		String html = "";
		try {
			String message = request.getParameter("message");
			request.setAttribute("message", message);
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("rouletteId", rouletteId);
			Czjroulette czjroulette = czjrouletteService.getCzjroulette(param);
			Map<String, Object> param4 = new HashMap<String, Object>();

			Map<String, Object> param5 = new HashMap<String, Object>();
			param5.put("shopId", rouletteId);
			List<CzjawardonVOR> czjawardonVORs = czjawardapiService.getawardonListALLVOR(param5);

			List<Czjawardstock> czjawardstocks  = czjawardstockService.getCzjawardstockListALL(param4);

			if("1".equals(czjroulette.getExt2())){
				html ="roulette/czjawardonEdit";
			}
			if("2".equals(czjroulette.getExt2())){
				html ="roulette/czjawardonEdit";
			}
			if("3".equals(czjroulette.getExt2())){
				html ="roulette/czjcodeEdit";
			}

			model.addAttribute("czjawardonVORs", czjawardonVORs);
			model.addAttribute("czjawardstocks", czjawardstocks);
			model.addAttribute("czjroulette", czjroulette);
			model.addAttribute("actionEdit", request.getParameter("actionEdit"));
			setDict(model);
		} catch (Exception e) {
			log.error("czjroulette edit error:", e);
			throw e;
		}
		return html;
	}

	/**
	 * czj_roulette  奖品编辑
	 *
	 * @param rouletteId
	 * @param ext3 抽取
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjawardDetails.do")
	public String czjawardDetails(String rouletteId,
								  HttpServletRequest request, ModelMap model) throws Exception{
		String html = "";
		try {
			String message = request.getParameter("message");
			request.setAttribute("message", message);
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("rouletteId", rouletteId);
			Czjroulette czjroulette = czjrouletteService.getCzjroulette(param);
			if(czjroulette.getActType()==1){
				html ="roulette/czjawardonDetails";
			}else{
				html ="roulette/czjcodeDetails";
			}
			Map<String, Object> param4 = new HashMap<String, Object>();
			Map<String, Object> param5 = new HashMap<String, Object>();
			param5.put("shopId", rouletteId);
			List<CzjawardonVOR> czjawardonVORs = czjawardapiService.getawardonListALLVOR(param5);


			List<Czjawardstock> czjawardstocks  = czjawardstockService.getCzjawardstockListALL(param4);

			model.addAttribute("czjawardonVORs", czjawardonVORs);
			model.addAttribute("czjawardstocks", czjawardstocks);
			model.addAttribute("czjroulette", czjroulette);
			model.addAttribute("actionEdit", request.getParameter("actionEdit"));
			setDict(model);
		} catch (Exception e) {
			log.error("czjroulette edit error:", e);
			throw e;
		}
		return html;
	}

	/**
	 * czj_roulette  奖品编辑
	 *
	 * @param rouletteId
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjawardonEdit.do")
	public String czjawardonEdit(String rouletteId,
								 Integer ext3,
								 HttpServletRequest request, ModelMap model) throws Exception{
		model.addAttribute("failed", request.getParameter("failed"));
		model.addAttribute("success", request.getParameter("success"));
		List<Map<String, Object>> listmap = setAward(rouletteId,model);
		Map<String,Map<String,Object>> objectMap = MapManage.toGetKeyMap("value", listmap);
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("rouletteId", rouletteId);
		List<Czjawardon> listawardon = czjawardonService.getListEntity(param);
		List<Map<String, Object>> listobj = ConvertObj.toListMap(listawardon);

		String thingId = null;
		Object thingIdObj = null;
		for (int i = 0; i < listobj.size(); i++) {
			thingIdObj = listobj.get(i).get("thingId");
			if(thingIdObj==null){
				listobj.get(i).put("distributable", "0");
				continue;
			}
			thingId = String.valueOf(thingIdObj);
			if(StringUtils.isBlank(thingId)){
				listobj.get(i).put("distributable", "0");
				continue;
			}

			if(objectMap.get(thingId)==null){
				listobj.get(i).put("distributable", "0");
				continue;
			}
			Object shengyu = objectMap.get(thingId).get("shengyunum")==null?0:objectMap.get(thingId).get("shengyunum");
			listobj.get(i).put("distributable", Integer.parseInt(String.valueOf(shengyu)));


		}
//		model.addAttribute("list", listawardon);
		model.addAttribute("list", listobj);
		model.addAttribute("rouletteId", rouletteId);
		return "roulette/czjawardoncodeEdit";
	/*	String html = "";
      try {
          String message = request.getParameter("message");
          request.setAttribute("message", message);
   		Map<String, Object> param = new HashMap<String, Object>();
   		param.put("rouletteId", rouletteId);
         Czjroulette czjroulette = czjrouletteService.getCzjroulette(param);
         if(czjroulette.getActType()==1){
        	 html ="roulette/czjawardonEdit";
         }else{
        	 html ="roulette/czjawardoncodeEdit";
         }
         Map<String, Object> param4 = new HashMap<String, Object>();
         Map<String, Object> param5 = new HashMap<String, Object>();
         param5.put("shopId", rouletteId);
         param5.put("endRows", ext3);
         List<CzjawardonVOR> czjawardonVORs = czjawardapiService.getawardonListALLVOR(param5);

         Map<String, Object> paramAll = new HashMap<String, Object>();
         paramAll.put("shopId", rouletteId);
         List<CzjawardonVOR> czjawardonVORs2  = czjawardapiService.getawardonListALLVOR(paramAll);

         //比较传的和实际大小
         Integer more = ext3 - czjawardonVORs2.size() ;


         //轮盘分多的时候
         if(more>0){
        	 List<Integer> integers =  new ArrayList<Integer>();
        	  for (int i = 0; i < more; i++) {
				int j = czjawardonVORs.size() + i+1;
				integers.add(j);
			}
        	 for(Integer integer : integers){
	        	 CzjawardonVOR czjawardonVOR = new CzjawardonVOR();
	        	 czjawardonVOR.setProbability(0.0);
	        	 czjawardonVOR.setExt1(String.valueOf(integer));
	        	 czjawardonVOR.setExt3("0");
	        	 //生成唯一码
	        	 czjawardonVOR.setAwardonId(UUIDUtils.getUUID());
	        	 //旧的thingId
	        	 czjawardonVOR.setThingId("-1");
	        	 czjawardonVORs.add(czjawardonVOR);
             }
         }
         //轮盘分少的时候          放到库存
         if(more<0){
        	 Map<String, Object> param6 = new HashMap<String, Object>();
        	 int index = czjawardonVORs2.size() + more;
        	 String endRows = index +","+ czjawardonVORs2.size();
        	 param6.put("endRows", endRows);
        	 List<CzjawardonVOR> czjawardons = czjawardapiService.getawardonListALLVOR(param6);
        	 for(CzjawardonVOR czjawardonVOR : czjawardons){
        		 if(czjawardonVOR.getExt3()==null){
        			 czjawardonVOR.setExt3("0");
        		 }
        		 if(czjawardonVOR.getCount()==null){
        			 czjawardonVOR.setCount(0);
        		 }
        		 int chuoqu = Integer.valueOf(czjawardonVOR.getExt3());
        		 int shengyu = czjawardonVOR.getCount() - chuoqu;
        		 Map<String, Object> param7 = new HashMap<String, Object>();
        		 param7.put("awardstockId", czjawardonVOR.getThingId());
        		 Czjawardstock czjawardstock = czjawardstockService.getCzjawardstock(param7);
        		 if(czjawardstock!=null){
        		 int shengyunum = czjawardstock.getShengyunum()+shengyu;
        		 czjawardstock.setShengyunum(shengyunum);
        		 czjawardstockService.updateCzjawardstock(czjawardstock);

        		  Map<String, Object> paramaward = new HashMap<String, Object>();
        		  paramaward.put("awardonId", czjawardonVOR.getAwardonId());
        		  czjawardonService.deleteCzjawardonByAwardonId(paramaward);
        		}
        	 }


         }



         List<Czjawardstock> czjawardstocks  = czjawardstockService.getCzjawardstockListALL(param4);

         model.addAttribute("czjawardonVORs", czjawardonVORs);
         model.addAttribute("czjawardstocks", czjawardstocks);
   		model.addAttribute("czjroulette", czjroulette);
         model.addAttribute("actionEdit", request.getParameter("actionEdit"));
         setDict(model);
         } catch (Exception e) {
   			log.error("czjroulette edit error:", e);
            throw e;
   		}
		return html;*/
	}

	/**
	 * 保存轮盘分配信息，第一次可以修改，有中奖信息的时候而且不是同一个奖品则不能再次修改
	 * 只能做更新操作
	 * @param prizePaths
	 * @param backgroundPath
	 * @param rouletteId
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("saveAwardon")
	public String saveAwardon(@RequestParam(required = false,name = "prizePath") MultipartFile[] prizePaths,//活动说明图片
							  @RequestParam(required = false,name = "backgroundPath") MultipartFile[] backgroundPath,//补充说明图片
							  String rouletteId,
							  HttpServletRequest request, ModelMap model ) throws Exception {

		/*if(true){
			return "redirect:czjawardonEdit.do?rouletteId="+rouletteId+"&failed="+URLEncoder.encode("测试中，暂不允许操作！","UTF-8");

		}*/

		String[] awardonIds = request.getParameterValues("awardonId");//轮盘分配奖品的id
		String[] ext1 = request.getParameterValues("ext1");//序号
		String[] thingIds = request.getParameterValues("thingId");//奖品库奖品id
		String[] counts = request.getParameterValues("count");//分配数量
//		String[] themes = request.getParameterValues("theme");
		String[] probabilitys = request.getParameterValues("probability");//概率
		for (int i = 0; i < counts.length; i++) {
			if(StringUtils.isBlank(counts[i])){
				counts[i]="0";
			}
			if(StringUtils.isBlank(probabilitys[i])){
				probabilitys[i]="0";
			}
		}
		if(thingIds==null||thingIds.length==0){
//			model.addAttribute("failed", "优惠活动的奖品必须有一个");
			return "redirect:czjawardonEdit.do?rouletteId="+rouletteId+"&failed="+URLEncoder.encode("优惠活动的奖品必须有一个","UTF-8");
		}
		for (String thingId : thingIds) {
			if(StringUtils.isBlank(thingId)){
				return "redirect:czjawardonEdit.do?rouletteId="+rouletteId+"&failed="+URLEncoder.encode("优惠活动的奖品必须有一个","UTF-8");

			}
		}
		for (int i = 0; i < awardonIds.length; i++) {
			Czjawardon entity = czjawardonService.queryById(awardonIds[i]);
			if(StringUtils.isBlank(entity.getThingId())){
				Czjawardstock awardstock = czjawardstockService.queryByAwardstockId(thingIds[i]);
				updateAwardon(ext1[i], thingIds[i], counts[i], probabilitys[i],prizePaths[i],backgroundPath[i], entity,request);
				awardstock.setShengyunum(awardstock.getShengyunum()-Integer.parseInt(counts[i]));
				awardstock.setChouqunum(awardstock.getChouqunum()+ Integer.parseInt(counts[i]));
				try {
					checkAwardstockAmount(awardstock);
				} catch (Exception e) {
					return "redirect:czjawardonEdit.do?rouletteId="+rouletteId+"&failed="+URLEncoder.encode(e.getMessage(),"UTF-8");

				}
				czjawardonService.updateCzjawardon(entity);
				czjawardstockService.updateCzjawardstock(awardstock);
				continue;
			}else if(entity.getThingId().equals(thingIds[i])){
				Czjawardstock awardstock = czjawardstockService.queryByAwardstockId(entity.getThingId());
				if(Integer.parseInt(counts[i])<entity.getExt3()){
					return "redirect:czjawardonEdit.do?rouletteId="+rouletteId+"&failed="+URLEncoder.encode("奖品（"+awardstock.getThingName()+"）数量不能少于中奖用户的数量（"+entity.getExt3()+"）","UTF-8");
				}
				int chazhi = Integer.parseInt(counts[i])-entity.getCount();//差值
				awardstock.setShengyunum(awardstock.getShengyunum()-chazhi);
				awardstock.setChouqunum(awardstock.getChouqunum()+chazhi);
				updateAwardon(ext1[i], thingIds[i], counts[i], probabilitys[i],prizePaths[i],backgroundPath[i], entity,request);
				try {
					checkAwardstockAmount(awardstock);
				} catch (Exception e) {
					return "redirect:czjawardonEdit.do?rouletteId="+rouletteId+"&failed="+URLEncoder.encode(e.getMessage(),"UTF-8");

				}
				czjawardonService.updateCzjawardon(entity);
				czjawardstockService.updateCzjawardstock(awardstock);
				continue;
			}else{
				if(entity.getExt3()==null||entity.getExt3()==0){
					Czjawardstock awardstock = czjawardstockService.queryByAwardstockId(entity.getThingId());
					awardstock.setChouqunum(awardstock.getChouqunum()-entity.getCount());//还原回奖品库 数据处理
					awardstock.setShengyunum(awardstock.getShengyunum()+entity.getCount());//还原回奖品库 数据处理

					Czjawardstock awardstock2 = czjawardstockService.queryByAwardstockId(thingIds[i]);
					awardstock2.setChouqunum(awardstock2.getChouqunum()+entity.getCount());//从奖品库分配 数据处理
					awardstock2.setShengyunum(awardstock2.getShengyunum()-entity.getCount());//从奖品库分配 数据处理

					updateAwardon(ext1[i], thingIds[i], counts[i], probabilitys[i],prizePaths[i],backgroundPath[i], entity,request);
					try {
						checkAwardstockAmount(awardstock);
						checkAwardstockAmount(awardstock2);
					} catch (Exception e) {
						return "redirect:czjawardonEdit.do?rouletteId="+rouletteId+"&failed="+URLEncoder.encode(e.getMessage(),"UTF-8");

					}
					czjawardonService.updateCzjawardon(entity);
					czjawardstockService.updateCzjawardstock(awardstock);
					czjawardstockService.updateCzjawardstock(awardstock2);
					continue;
				}
				return "redirect:czjawardonEdit.do?rouletteId="+rouletteId+"&failed="+URLEncoder.encode("优惠活动已有中奖信息不能更改奖品，只允许修改数量和概率等","UTF-8");
			}


			
		}
		
		
		

		return "redirect:czjrouletteActList.do";
	}

	/**
	 * 检查奖品库剩余数量和分配数量
	 * @param awardstock
	 */
	private void checkAwardstockAmount(Czjawardstock awardstock) throws Exception {

		if(awardstock.getShengyunum()<0){
			throw new Exception("奖品库剩余数量不足，请检查奖品（"+awardstock.getThingName()+"）");
		}
		if(awardstock.getChouqunum()<0){
			throw new Exception("奖品库分配数量不足，请检查奖品（"+awardstock.getThingName()+"）");
		}
	}

	private void updateAwardon(String ext1, String thingId, String count, String probability, MultipartFile prizePaths, MultipartFile backgroundPath, Czjawardon entity, HttpServletRequest request) throws Exception {
		entity.setThingId(thingId);
		entity.setExt1(ext1);
		entity.setCount(Integer.parseInt(count));
		entity.setProbability(new Double(probability));
		setPrizePath(entity,prizePaths,request);
		setBackgroundPath(entity,backgroundPath,request);


	}

	/**
	 *	 根据奖品库奖品id 获取剩余数量
	 * @param thingId 奖品库奖品id
	 * @param request
	 * @param response
	 * @param model
	 * @throws IOException
	 */
	@RequestMapping("getAwardstockSY.do")
	public void getAwardstockSY(@RequestParam(required = true) String thingId, HttpServletRequest request, HttpServletResponse response, ModelMap model) throws IOException {
		Czjawardstock stock = czjawardstockService.queryById(thingId);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("shengyuNum",stock.getShengyunum()==null?0:stock.getShengyunum());
		response.getOutputStream().print(JSONObject.toJSONString(map));
	}

	//把实体的数量分配到奖品
	private void distributionNum(Czjawardstock stock, Czjawardon entity,int distributionCount) {
		int chazhi = distributionCount-entity.getCount();//差值=分配的数量-已退还后奖品的数量
		int shengyu = stock.getCountnum()-stock.getChouqunum();
		stock.setShengyunum(shengyu-chazhi);
		stock.setChouqunum(stock.getChouqunum()+chazhi);
		entity.setCount(distributionCount);
	}
	//把实体的数量还原到库中
	private void restoreNum(Czjawardstock stock, Czjawardon entity) {
		int chazhi = entity.getCount()-entity.getExt3();
		int shengyu = stock.getCountnum()-stock.getChouqunum();
		stock.setShengyunum(shengyu+chazhi);
		stock.setChouqunum(stock.getChouqunum()-chazhi);
		entity.setCount(entity.getExt3());
	}

	/**
	 * 上传补充说明图片
	 */
	private void setBackgroundPath(Czjawardon czjawardon, MultipartFile multipartFile, HttpServletRequest req) throws Exception {
		if((!multipartFile.isEmpty())&&multipartFile.getSize()>0){
			String basePath = req.getSession().getServletContext().getRealPath("/");
			String path = basePath+"upload/awardon/backgroundPath/"+czjawardon.getAwardonId()+"-"+ System.currentTimeMillis()+multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
			Fileupload.createDir(basePath+"upload/awardon/backgroundPath/");

			InputStream in = multipartFile.getInputStream();
			FileOutputStream out = new FileOutputStream(path);
			try {
				IOUtils.copy(in,out);
			} catch (IOException e) {
				e.printStackTrace();
				throw new Exception("上传图片失败！");
			}finally {
				IOUtils.closeQuietly(in);
				IOUtils.closeQuietly(out);
			}

			String picPath = "/"+path.replace(basePath, "");
			czjawardon.setBackgroundPath(picPath);
		}
	}

	/**
	 * 上传活动说明图片
	 * @param czjawardon
	 * @param multipartFile
	 * @param req
	 * @throws Exception
	 */
	private void setPrizePath(Czjawardon czjawardon, MultipartFile multipartFile, HttpServletRequest req) throws Exception {
		if((!multipartFile.isEmpty())&&multipartFile.getSize()>0){
			String basePath = req.getSession().getServletContext().getRealPath("/");
			String path = basePath+"upload/awardon/prizePath/"+czjawardon.getAwardonId()+"-"+ System.currentTimeMillis()+multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
			Fileupload.createDir(basePath+"upload/awardon/prizePath/");

			InputStream in = multipartFile.getInputStream();
			FileOutputStream out = new FileOutputStream(path);
			try {
				IOUtils.copy(in,out);
			} catch (IOException e) {
				e.printStackTrace();
				throw new Exception("上传图片失败！");
			}finally {
				IOUtils.closeQuietly(in);
				IOUtils.closeQuietly(out);
			}

			String picPath = "/"+path.replace(basePath, "");
			czjawardon.setPrizePath(picPath);
		}
	}

	/**
	 * 选择奖品名、奖品总数、奖品剩余数量
	 * @param rouletteId
	 * @param model
	 */
	public List<Map<String, Object>> setAward(String rouletteId, ModelMap model){
		Map<String,Object> param = new HashMap<String,Object>();
		List<Map<String,Object>> listAwardId = czjawardstockService.getListAwardId(param);
		String thingName = "";
		String shengyunum="";
		String chouquNum ="";
		int count = 0;
		String countNum = "";
		String awardstockId="";
		Map<String, Object> param2 = new HashMap<String, Object>();
		param2.put("rouletteId", rouletteId);
		List<Czjawardon> listawardon = czjawardonService.getListEntity(param2);
		//整合该优惠活动分配的种类的数量
		Map<String, Integer> mapEntity = new HashMap<String, Integer>();
		for (Czjawardon czjawardon : listawardon) {
			if(mapEntity.get(czjawardon.getThingId())==null){
				mapEntity.put(czjawardon.getThingId(), 0);
			}
			mapEntity.put(czjawardon.getThingId(), mapEntity.get(czjawardon.getThingId())+czjawardon.getCount());
		}

		List<Map<String, Object>> listAwardId2= new ArrayList<Map<String, Object>>();
		Map<String, Object> map = new HashMap<String, Object>();

		for (Map<String, Object> objectMap : listAwardId) {
			map = new HashMap<String, Object>();
			thingName = String.valueOf(objectMap.get("thingName"));
			shengyunum = String.valueOf(objectMap.get("shengyunum"));
			countNum = String.valueOf(objectMap.get("countnum"));
			chouquNum = String.valueOf(objectMap.get("chouqunum"));
			awardstockId = String.valueOf(objectMap.get("value"));
//			map.put("name", thingName+" （"+countNum+"/"+shengyunum+"）");
			map.put("name", thingName);
			map.put("value",String.valueOf(objectMap.get("value")) );
			if(mapEntity.get(awardstockId)!=null){
				count = Integer.valueOf(shengyunum)+mapEntity.get(awardstockId);
//				map.put("name", "奖品："+thingName+" ；可分配数量："+count);
//				map.put("name", thingName+" （"+countNum+"/"+shengyunum+"）");
				map.put("name", thingName);
			}


			listAwardId2.add(map);
		}
		model.addAttribute("listAwardId", listAwardId2);
		return listAwardId;
	}

	/**
	 * czj_roulette  二维码
	 *
	 * @param rouletteId
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjrouletteCodeEdit.do")
	public String czjrouletteCodeEdit(String rouletteId, HttpServletRequest request, ModelMap model) throws Exception{

		try {
			String message = request.getParameter("message");
			request.setAttribute("message", message);
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("rouletteId", rouletteId);
			Czjroulette czjroulette = czjrouletteService.getCzjroulette(param);
			Map<String, Object> param4 = new HashMap<String, Object>();

			Map<String, Object> param5 = new HashMap<String, Object>();
			param5.put("shopId", rouletteId);
			List<CzjawardonVOR> czjawardonVORs = czjawardapiService.getawardonListALLVOR(param5);

			List<Czjawardstock> czjawardstocks  = czjawardstockService.getCzjawardstockListALL(param4);

			model.addAttribute("czjawardonVORs", czjawardonVORs);
			model.addAttribute("czjawardstocks", czjawardstocks);
			model.addAttribute("czjroulette", czjroulette);
			model.addAttribute("actionEdit", request.getParameter("actionEdit"));
			setDict(model);
		} catch (Exception e) {
			log.error("czjroulette edit error:", e);
			throw e;
		}
		return "roulette/czjcodeEdit";
	}

	/**
	 * czj_roulette  优惠编辑页面
	 *
	 * @param rouletteId
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjrouletteActEdit.do")
	public String czjrouletteEdit(String rouletteId, HttpServletRequest request, ModelMap model) throws Exception{
		try {
			String message = request.getParameter("message");
			request.setAttribute("message", message);
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("rouletteId", rouletteId);
			Czjroulette czjroulette = czjrouletteService.getCzjroulette(param);
			Map<String, Object> param4 = new HashMap<String, Object>();

			Map<String, Object> param5 = new HashMap<String, Object>();
			param5.put("shopId", rouletteId);
			List<CzjawardonVOR> czjawardonVORs = czjawardapiService.getawardonListALLVOR(param5);

			List<Czjawardstock> czjawardstocks  = czjawardstockService.getCzjawardstockListALL(param4);

			model.addAttribute("czjawardonVORs", czjawardonVORs);
			model.addAttribute("czjawardstocks", czjawardstocks);
			model.addAttribute("czjroulette", czjroulette);
			model.addAttribute("actionEdit", request.getParameter("actionEdit"));
			setDict(model);
		} catch (Exception e) {
			log.error("czjroulette edit error:", e);
			throw e;
		}
		return "roulette/czjrouletteActEdit";
	}

	/**
	 * czj_roulette  优惠编辑页面
	 *
	 * @param rouletteId
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjrouletteEdit.do")
	public String edit(String rouletteId, HttpServletRequest request, ModelMap model) throws Exception{
		String  html ="";
		model.addAttribute("failed", request.getParameter("failed"));
		model.addAttribute("success", request.getParameter("success"));
		try {
			String message = request.getParameter("message");
			request.setAttribute("message", message);
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("rouletteId", rouletteId);
			Czjroulette czjroulette = czjrouletteService.getCzjroulette(param);
			Map<String, Object> param4 = new HashMap<String, Object>();

			Map<String, Object> param5 = new HashMap<String, Object>();
			param5.put("shopId", rouletteId);
			List<CzjawardonVOR> czjawardonVORs = czjawardapiService.getawardonListALLVOR(param5);

			List<Czjawardstock> czjawardstocks  = czjawardstockService.getCzjawardstockListALL(param4);

			if(czjroulette.getActType()==1){
				html ="roulette/czjrouletteEdit";
			}else{
				html ="roulette/czjcodeEdit";
			}
			model.addAttribute("czjawardonVORs", czjawardonVORs);
			model.addAttribute("czjawardstocks", czjawardstocks);
			model.addAttribute("czjroulette", czjroulette);
			model.addAttribute("actionEdit", request.getParameter("actionEdit"));
			setDict(model);
		} catch (Exception e) {
			log.error("czjroulette edit error:", e);
			throw e;
		}
		return html;
	}

	/**
	 * czj_roulette  优惠详情
	 *
	 * @param rouletteId
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjrouletteDetail.do")
	public String detail(String rouletteId, HttpServletRequest request, HttpServletResponse response, ModelMap model) throws Exception{
		try {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("rouletteId", rouletteId);
			Czjroulette czjroulette = czjrouletteService.getCzjroulette(param);
			model.addAttribute("czjroulette", czjroulette);
			setDict(model);
		} catch (Exception e) {
			log.error("czjroulette detail error:", e);
			throw e;
		}
		return "roulette/czjrouletteView";
	}


	/**
	 * czj_roulette  优惠详情
	 *
	 * @param rouletteId
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("rouletteQueryImgOrder.do")
	public void detail1111(String imgOrder, String rouletteId,String ext2, HttpServletRequest request, HttpServletResponse response, ModelMap model) throws Exception{
		try {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("imgOrder", imgOrder);
			param.put("ext2", ext2);
			Czjroulette czjroulette = czjrouletteService.queryImgOrder(param);

			//插入时
			if("".equals(rouletteId)){
				if(czjroulette !=null){
					jsonResult(1,"","重复的顺序",0,response);
				}else{
					jsonResult(1,"","可以添加",1,response);
				}
			}
			//更新时
			if(!"".equals(rouletteId)){
				//查询自己
				Map<String, Object> paramMy = new HashMap<String, Object>();
				paramMy.put("rouletteId", rouletteId);
				Czjroulette myorder = czjrouletteService.getCzjroulette(paramMy);
				String myordernum = myorder.getImgOrder();
				//和自己相同的可以更新
				if(myordernum.equals(imgOrder)){
					jsonResult(1,"","可以添加",1,response);
				}else{
					//如果跟自己的不相同
					List<String> listString = czjrouletteService.getCzjrouletteALL(param);
					System.out.println(listString);
					boolean flag = true;
					//循环数据库字段,如果相同,就代表有重复
					for(String str : listString){
						if(imgOrder.equals(str)){
							flag= false;
						}
					}
					System.out.println(flag);
					if(!flag){
						jsonResult(1,"","重复的顺序",0,response);
					}else{
						jsonResult(1,"","可以添加",1,response);
					}


				}



			}



		} catch (Exception e) {
			jsonResult(1,"","系统异常","",response);
			log.error("czjroulette detail error:", e);
			throw e;
		}

	}

	/**
	 * czj_roulette  轮盘列表线上（分页）
	 *
	 * @param czjroulette
	 * @param pageNo
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjrouletteActList.do")
	public String czjrouletteActList(Czjroulette czjroulette, Integer pageNo, String order,
									 String sort,HttpServletRequest request, ModelMap model) throws Exception{
		try {
			if (pageNo == null)
				pageNo = 1;
			Pagination pagination = czjrouletteService.getCzjrouletteList(toMap(czjroulette), 10, pageNo,order, sort);
			request.setAttribute("actname",czjroulette.getActname());
			request.setAttribute("actType", czjroulette.getActType());
			model.addAttribute("pagination", pagination);
			setDict(model);
		} catch (Exception e) {
			log.error("czjroulette listPage error:", e);
			throw e;
		}
		return "roulette/czjrouletteActList";
	}

	/**
	 * czj_roulette  轮盘列表线上（分页）
	 *
	 * @param czjroulette
	 * @param pageNo
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjrouletteList.do")
	public String listPage(Czjroulette czjroulette, Integer pageNo, String order,
						   String sort,HttpServletRequest request, ModelMap model) throws Exception{
		try {
			if (pageNo == null)
				pageNo = 1;
			czjroulette.setExt2("1");
			Pagination pagination = czjrouletteService.getCzjrouletteList(toMap(czjroulette), 10, pageNo,
					order, sort);
			request.setAttribute("ext2", 1);
			model.addAttribute("pagination", pagination);
			setDict(model);
		} catch (Exception e) {
			log.error("czjroulette listPage error:", e);
			throw e;
		}
		return "roulette/czjrouletteList";
	}

	/**
	 * czj_roulette  轮盘列表线下（分页）
	 *
	 * @param czjroulette
	 * @param pageNo
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjrouletteoffList.do")
	public String listPageczjrouletteoffList(Czjroulette czjroulette, Integer pageNo, String order,
											 String sort,HttpServletRequest request, ModelMap model) throws Exception{
		try {
			if (pageNo == null)
				pageNo = 1;
			czjroulette.setExt2("2");
			Pagination pagination = czjrouletteService.getCzjrouletteList(toMap(czjroulette), 10, pageNo,
					order, sort);
			request.setAttribute("ext2", 2);
			model.addAttribute("pagination", pagination);
			setDict(model);
		} catch (Exception e) {
			log.error("czjroulette listPage error:", e);
			throw e;
		}
		return "roulette/czjrouletteList";
	}

	/**
	 * czj_roulette  轮盘列表线下（分页）
	 *
	 * @param czjroulette
	 * @param pageNo
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjcodeList.do")
	public String czjcodeList(Czjroulette czjroulette, Integer pageNo, String order,
							  String sort,HttpServletRequest request, ModelMap model) throws Exception{
		try {
			if (pageNo == null)
				pageNo = 1;
			czjroulette.setExt2("3");
			Pagination pagination = czjrouletteService.getCzjrouletteList(toMap(czjroulette), 10, pageNo,
					order, sort);
			request.setAttribute("ext2", 3);
			model.addAttribute("pagination", pagination);
			setDict(model);
		} catch (Exception e) {
			log.error("czjroulette listPage error:", e);
			throw e;
		}
		return "roulette/czjcodeList";
	}


	/**
	 * czj_roulette  优惠查询
	 *
	 * @param czjroulette
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjrouletteList1.do")
	public String list(Czjroulette czjroulette, HttpServletRequest request, ModelMap model) throws Exception{
		try {
			Map<String,Object> map = czjrouletteService.getCzjrouletteList(toMap(czjroulette));
			model.addAttribute("list", map.get("rows"));
			model.addAttribute("total", map.get("total"));
			setDict(model);
		} catch (Exception e) {
			log.error("czjroulette list error:", e);
			throw e;
		}
		return "roulette/czjrouletteList";
	}


	/***
	 * 将页面输入信息转成map
	 *
	 * @param czjroulette
	 * @return
	 */	private Map<String,Object> toMap(Czjroulette czjroulette){
		Map<String,Object> map=new HashMap<String, Object>();
		if(czjroulette.getRouletteId()!=null&&!czjroulette.getRouletteId().equals("")){
			map.put("rouletteId", czjroulette.getRouletteId());
		}
		if(czjroulette.getImgOrder()!=null&&!czjroulette.getImgOrder().equals("")){
			map.put("imgOrder", czjroulette.getImgOrder());
		}
		if(czjroulette.getImgPath()!=null&&!czjroulette.getImgPath().equals("")){
			map.put("imgPath", czjroulette.getImgPath());
		}
		if(czjroulette.getImgUrl()!=null&&!czjroulette.getImgUrl().equals("")){
			map.put("imgUrl", czjroulette.getImgUrl());
		}
		if(czjroulette.getRemark()!=null&&!czjroulette.getRemark().equals("")){
			map.put("remark", czjroulette.getRemark());
		}
		if(czjroulette.getCreatetime()!=null&&!czjroulette.getCreatetime().equals("")){
			map.put("createtime", czjroulette.getCreatetime());
		}
		if(czjroulette.getExt1()!=null&&!czjroulette.getExt1().equals("")){
			map.put("ext1", czjroulette.getExt1());
		}
		if(czjroulette.getExt2()!=null&&!czjroulette.getExt2().equals("")){
			map.put("ext2", czjroulette.getExt2());
		}
		if(czjroulette.getExt3()!=null&&!czjroulette.getExt3().equals("")){
			map.put("ext3", czjroulette.getExt3());
		}
		if(czjroulette.getActname()!=null&&!czjroulette.getActname().equals("")){
			map.put("actname", czjroulette.getActname());
		}
		if(czjroulette.getActType()!=null&&!czjroulette.getActType().equals("")){
			map.put("actType", czjroulette.getActType());
		}		
		return map;
	}

	/**
	 * 设置页面所需的数据字典
	 * @param model
	 */
	private void setDict(ModelMap model){

	}

	//删除更新的图片
	public void deleteFile(String jgpName){
		File f = new File(jgpName); // 输入要删除的文件位置
		if(f.exists()){
			f.delete();
		}

	}

	@Resource
	private CzjawardstockService czjawardstockService ;

	@Resource
	private CzjrouletteService czjrouletteService;

	@Resource
	private CzjawardapiService czjawardapiService;

	@Resource
	private CzjawardonService czjawardonService;


}